<template>
	<Layout style="padding:0 24px 24px;height:100%;">
		<Breadcrumb style="margin:24px 0">
			<BreadcrumbItem>首页</BreadcrumbItem>
			<BreadcrumbItem>规则调试</BreadcrumbItem>
		</Breadcrumb>
		<Content ref="content" style="padding:50px;background:#fff;height:100%">
			<Form ref="form" :model="info" :label-width="100" :rules="rules">
				<FormItem label="选择规则" prop="ruleCode">
					<Select style="min-width: 200px;" placeholder="请选择规则" v-model="info.ruleCode" :remote-method="list" remote filterable clearable>
						<Option v-for="item in ruleOptions" :key="item.ruleCode" :value="item.ruleCode" :label="item.ruleName"></Option>
					</Select>
				</FormItem>
				<FormItem label="规则内容" prop="ruleData"><Input :rows="15" v-model="ruleData" type="textarea" :placeholder="'a = 5\nb = 9'" /></FormItem>
				<FormItem label="规则内容"><Input :rows="5" v-model="resData" type="textarea" placeholder="显示运行结果" /></FormItem>
				<FormItem><Button type="primary" @click="execute">执行</Button></FormItem>
			</Form>
		</Content>
	</Layout>
</template>

<script language="JavaScript">
export default {
	components: {},
	data() {
		return {
			ruleData: '', // 字符串
			resData: '', // 结果数据
			info: {
				ruleCode: '', // 规则编号
				ruleData: {} // 规则数据
			},
			rules: {
				ruleCode: [
					{
						required: true,
						message: '必填'
					}
				]
			},
			// 分页请求
			pageRequest: {
				page: 1,
				rows: 3,
				sort: 'id:asc',
				condition: {}
			},
			// 规则选项
			ruleOptions: []
		};
	},
	computed: {},
	watch: {
		ruleData: function() {
			let arr = this.ruleData.split('\n') || [];
			this.info.ruleData = {};
			if (arr && arr.length > 0) {
				arr.forEach(str => {
					str.match(/\s*(.*?)\s*=\s*(.*)\s*/);
					if (RegExp.$1 && RegExp.$2) {
						let key = RegExp.$1,
							val = RegExp.$2;
						if (this.$utils.isDecimal(val)) {
							val = parseFloat(val);
						}
						this.info.ruleData[key] = val;
					}
				});
			}
		}
	},
	created: function() {},
	mounted: function() {
		this.list();
	},
	methods: {
		// 执行规则
		execute: function() {
			this.$refs['form'].validate(valid => {
				if (valid) {
					this.$request.post(
						'/admin/sys/drools/drl/execute',
						this.info,
						res => {
							this.resData = JSON.stringify(res.data.ruleData);
						},
						true,
						true
					);
				}
			});
		},
		// 获取列表
		list: function(kw) {
			this.pageRequest.condition.ruleName = kw || '';
			this.$request.post(
				'/admin/sys/drools/drl/list',
				this.pageRequest,
				res => {
					let pageData = res.data || {};
					this.ruleOptions = pageData.content || [];
				},
				false,
				false
			);
		}
	}
};
</script>

<style lang="scss" scoped="scoped"></style>
